package L01;

import java.io.*;
import java.util.Scanner;

public class IO02 {

    public static void main5 (String[] args) throws IOException {
        OutputStream out=new FileOutputStream ("output.txt");
        out.write ('H');
        out.write ('e');
        out.write ('l');
        out.write ('l');
        out.write ('o');
        out.flush ();//将缓冲区刷新到设备中

    }

    public static void main (String[] args) throws IOException {
        OutputStream out=new FileOutputStream ("output.txt",true);//在流的构造方法中引入true后，不会对文件原来存在的信息进行覆盖
        byte[] bit=new byte[]{'G','o','o','d'};
        out.write (bit);
        out.flush ();

    }




    //input和output是相对于计算机而言，文件的信息读取就是input，对文件的写入操作就是output

    public static void main4 (String[] args) throws IOException {//Scanner实现inputStream
        try (InputStream in = new FileInputStream ("hello2.txt")){
            Scanner scan=new Scanner (in,"UTF-8");
            while(scan.hasNext ()){
                String s=scan.next ();
                System.out.println (s);
            }
        }
    }

    public static void main3 (String[] args) throws IOException {
        try(InputStream in =new FileInputStream ("hello2.txt")){
            byte[] bit=new byte[1024];
            int len;
            while(true){
                len=in.read (bit);
                if(len==-1){
                    break;
                }

                for (int i = 0; i < len; i+=3) {
                    String s=new String (bit,i,3,"UTF-8");
                    System.out.printf ("%s",s);
                }
            }
        }
    }

    public static void main2 (String[] args) throws IOException {
        try(InputStream in =new FileInputStream ("hello.txt")){
            int len;
            byte[] bit=new byte[1024];
            while(true){
                len=in.read (bit);//此处的read方法直接读到字符尾，返回字符的长度，并将读到的字符储存到字符数组中
                //下一次while（）循环中，会返回-1，表示已经读到文件末尾
                //System.out.println (len);
                if(len==-1){break;}
                for (int i = 0; i < len; i++) {
                    System.out.printf ("%c",bit[i]);
                }
            }
        }
    }

    public static void main1 (String[] args) throws IOException {
        try(InputStream in =new FileInputStream ("hello.txt")){
            while(true){
                int b=in.read ();//read()方法读取一个字节的数据，返回-1说明数据已经读完
                //此处的read（）方法是一个一个读的
                //System.out.println (" ");
                if(b==-1){
                    break;
                }
                System.out.printf("%c",b);
            }
        }
    }
}
